package com.ayou.eggguard.farm.controller;

import com.ayou.common.utils.Result;
import com.ayou.eggguard.farm.pojo.Abnormal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import weka.classifiers.Classifier;
import weka.core.*;
import weka.core.converters.ConverterUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/predict")
public class PredictController {

    @PostMapping
    public Result<List<Map<String,Object>>> getDiseaseType(@RequestBody Abnormal abnormal) throws Exception {
        ConverterUtils.DataSource source = new ConverterUtils.DataSource("D:/dataset.arff");
        Instances data = source.getDataSet();
        if (data.classIndex() == -1)
            data.setClassIndex(data.numAttributes() - 1);
        Classifier loadedModel= (Classifier) SerializationHelper.read("D:/dataset.model");
        Instance newInst=new DenseInstance(7);
        newInst.setDataset(data);
        newInst.setValue(0,abnormal.getTemperature());
        newInst.setValue(1,abnormal.getMentalStatus());
        newInst.setValue(2,abnormal.getFacesStatus());
        newInst.setValue(3,abnormal.getBreathStatus());
        newInst.setValue(4,abnormal.getNerveStatus());
        newInst.setValue(5,abnormal.getCombColor());
        newInst.setValue(6,abnormal.getEggStatus());
        double[] probabilities=loadedModel.distributionForInstance(newInst);
        List<Map<String,Object>> list=new ArrayList<>();
        Attribute classAttribute=data.classAttribute();
        for(int i=0;i<probabilities.length;i++){
            String className=classAttribute.value(i);
            Map<String, Object> result = new HashMap<>();
            result.put("className",className);
            result.put("probability",probabilities[i]);
            list.add(result);
        }
        return Result.success(list);
    }
}
